package com.sc.order.service.impl;

import com.sc.common.pojo.CommonResult;
import com.sc.order.pojo.OrderInfo;
import com.sc.mapper.TbOrderItemMapper;
import com.sc.mapper.TbOrderMapper;
import com.sc.mapper.TbOrderShippingMapper;
import com.sc.order.component.JedisClient;
import com.sc.order.service.OrderService;
import com.sc.pojo.TbOrderItem;
import com.sc.pojo.TbOrderShipping;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;


/**
 * @auther sc
 * @Date 2017/11/7
 */
@Service
public class OrderServiceImpl implements OrderService {
    @Autowired
    private TbOrderMapper orderMapper;
    @Autowired
    private TbOrderItemMapper orderItemMapper;
    @Autowired
    private TbOrderShippingMapper orderShippingMapper;
    @Autowired
    private JedisClient jedisClient;

    @Value("${ORDER_NO}")
    private String ORDER_NO;

    @Value("${ORDER_BEGIN}")
    private String ORDER_BEGIN;

    @Value("${ORDER_DETAIL_NO}")
    private String ORDER_DEATIL_NO;

    @Override
    public CommonResult createOrder(OrderInfo orderInfo) {
        Long orderNo = getOrderNo();
        orderInfo.setOrderId(orderNo.toString());
        orderInfo.setStatus(1);
        orderMapper.insert(orderInfo);

        List<TbOrderItem> orderItems = orderInfo.getOrderItems();
        for (TbOrderItem item:orderItems) {
            Long orderDetailId = jedisClient.incr(ORDER_DEATIL_NO);
            item.setId(orderDetailId.toString());
            item.setOrderId(orderNo.toString());
            orderItemMapper.insert(item);
        }
        //物流表
        TbOrderShipping orderShipping = orderInfo.getOrderShipping();
        orderShipping.setOrderId(orderNo.toString());
        orderShippingMapper.insert(orderShipping);
        return CommonResult.ok(orderNo);
    }






    public Long getOrderNo(){
        String id = jedisClient.get(ORDER_NO);
        if(StringUtils.isBlank(id)){
            jedisClient.set(ORDER_NO,ORDER_BEGIN);
        }
       return jedisClient.incr(ORDER_NO);
    }


}
